package top.shiyiri.preparedstatement;

import org.junit.Test;
import top.shiyiri.bean.Customer;
import top.shiyiri.bean.Order;
import top.shiyiri.bean.User;
import top.shiyiri.util.JDBCUtils;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Aunean
 * @date 2022/1/17 16:53
 * @Description 使用 PreparedStatement 实现不同表的通用查询操作
 */
public class PreparedStatementQueryTest {

    /*
    针对不同的表的通用的查询操作，返回表中的一条记录
     */
    public static <T> T getInstance(Class<T> clazz, String sql, Object ... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);

            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1, args[i]);
            }
            //执行，获取结果集
            rs = ps.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();//获取列数
            if (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取每个列的列名
                    //String columnName = metaData.getColumnName(i+1);
                    //获取列的别名
                    String columnLabel = metaData.getColumnLabel(i+1);
                    //获取每个列的列值
                    Object columnValue = rs.getObject(i + 1);

                    //通过反射，将对象指定名columnName的属性赋值为指定的值columnValue
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);//保证私有属性也可以访问
                    field.set(t, columnValue);//赋值
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps, rs);
        }
        return null;
    }

    @Test
    public void testGetInstance() {
        String sql = "select id, name, email, birth from customers where id = ?";
        Customer instance = getInstance(Customer.class, sql, 5);
        System.out.println(instance);

        String sql1 = "select order_id orderId, order_name orderName, order_date orderDate from `order` where order_id = ?";
        Order instance1 = getInstance(Order.class, sql1, 2);
        System.out.println(instance1);
    }

    /*
    针对不同的表的通用的查询操作，返回一个List集合
     */
    public static<T> List<T> getForList(Class<T> clazz, String sql, Object ... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);

            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1, args[i]);//填充占位符
            }
            //执行，获取结果集
            rs = ps.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData metaData = rs.getMetaData();
            //创建集合对象
            ArrayList<T> list = new ArrayList<>();
            int columnCount = metaData.getColumnCount();//获取列数
            while (rs.next()) {
                T t = clazz.newInstance();
                //处理结果集数据中的每一列，给t对象指定的属性赋值
                for (int i = 0; i < columnCount; i++) {
                    //获取列的别名
                    String columnLabel = metaData.getColumnLabel(i+1);
                    //获取每个列的列值
                    Object columnValue = rs.getObject(i + 1);

                    //通过反射，将对象指定名columnName的属性赋值为指定的值columnValue
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);//保证私有属性也可以访问
                    field.set(t, columnValue);//赋值
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps, rs);
        }
        return null;
    }

    @Test
    public void getForListTest() {
        String sql = "select * from user";
        List<User> list = getForList(User.class, sql);
        list.forEach(System.out::println);

        System.out.println("*************************");

        String sql2 = "select id, name, email, birth from customers where id > ?";
        List<Customer> list2 = getForList(Customer.class, sql2, 10);
        list2.forEach(System.out::println);

        System.out.println("*************************");

        String sql3 = "select id, name, email, birth from customers limit ?,?";
        List<Customer> list3 = getForList(Customer.class, sql3, 5, 3);
        list3.forEach(System.out::println);
    }
}
